package com.chb.service.impl;

import com.chb.dao.BranchGoodsDao;
import com.chb.dao.OutLibrayDao;
import com.chb.dao.OutLibrayGoodsDao;
import com.chb.model.entity.*;
import com.chb.model.vo.BranchGoodsVo;
import com.chb.model.vo.OutLibrayVo;
import com.chb.model.vo.PageBean;
import com.chb.model.vo.Result;
import com.chb.service.OutLibrayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author: 陈海彬
 * @date: Created in 2023/9/28 20:03
 * @description:
 * @modified By:
 * @version:
 */
@Service
public class OutLibrayServiceImpl implements OutLibrayService {
    @Autowired
    private BranchGoodsDao branchGoodsDao;
    @Autowired
    private OutLibrayDao outLibrayDao;
    @Autowired
    private OutLibrayGoodsDao outLibrayGoodsDao;
    @Autowired
    HttpSession session;

    @Override
    public Result getInformation(Integer branchid, Integer page, Integer pageSize) {
        //1.获取session
        Staff staff = (Staff) session.getAttribute("staff");
        //2.设置分页的数量
        PageHelper.startPage(page, pageSize);
        //3.进行查询
        List<BranchGoodsVo> branchGoodsList = null;
        /**
         * 1代表开启模糊查询，0代表初始化不开启
         */
        if (branchid == null) {
            branchGoodsList = branchGoodsDao.selectBranchByBranchidAndCounts(staff.getBranchid(), staff.getStaffid(), 0);
        } else {
            //进行模糊查询
            branchGoodsList = branchGoodsDao.selectBranchByBranchidAndCounts(branchid, staff.getStaffid(), 1);
        }
        //4.进行分页
        PageInfo<BranchGoodsVo> pageInfo = new PageInfo<>(branchGoodsList);
        //5.进行封装分页后的数据
        PageBean<BranchGoodsVo> pageBean = new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
        return Result.success(pageBean);
    }

    @Override
    @Transactional
    public Result addOutLibray(List<BranchGoodsVo> branchGoodsVoList, Integer outmethod) {
        //1.获取session
        Staff staff = (Staff) session.getAttribute("staff");

        //创建一个入库实体类
        OutLibray outLibray = new OutLibray();
        //2.进行赋值操作
        outLibray.setOutstaffid(staff.getStaffid()); //设置操作者
        outLibray.setOuttime(new Date(System.currentTimeMillis())); //设置出库时间
        outLibray.setExamstate(1);  //设置审核状态  1代表待审核
        outLibray.setBranchid(staff.getBranchid());//设置所属分店
        //设置批量或零售状态
        outLibray.setOutmethod(outmethod);


        //3.执行sql操作————返回主键
        Integer cid = outLibrayDao.addOutLibray(outLibray);

        //4.进行遍历列表
        for (BranchGoodsVo branchGoodsVo : branchGoodsVoList) {
            //获取出库的数量
            Integer incounts = branchGoodsVo.getIncounts();

            //5.创建出库商品实体类
            OutLibrayGoods outLibrayGoods = new OutLibrayGoods(null, outLibray.getCid(), branchGoodsVo.getGoodsid(), incounts, branchGoodsVo.getGoods().getCprice() * incounts, null);
            //6.执行sql操作
            outLibrayGoodsDao.addOutLibrayGoods(outLibrayGoods);

            if (outmethod.equals(1)) { //进行零售出库
                outLibray.setExamstate(2);//设置审核状态
                outLibray.setExamstaffid(staff.getStaffid());//设置审核人
                outLibray.setExamtime(new Date(System.currentTimeMillis()));//设置审核时间
                //减少库存
                this.reduceCounts(outLibrayGoods, staff.getBranchid());
                //进行审核通过
                outLibrayDao.updateOutLibray(outLibray);
            }
        }

        return Result.success();
    }

    @Override
    public Result getWarehouseInfo(Integer page, Integer pageSize, Integer branchid) {
        //1.获取session
        Staff staff = (Staff) session.getAttribute("staff");
        //2.设置分页
        PageHelper.startPage(page, pageSize);
        /**
         * 1代表开启模糊查询，0代表初始化不开启
         */
        List<OutLibrayVo> librayVoList = null;
        if (branchid == null) {
            //3.进行查询
            librayVoList = outLibrayDao.findOutLibrayByBranchid(staff.getStaffid(), staff.getBranchid(), 0);
        } else {
            librayVoList = outLibrayDao.findOutLibrayByBranchid(staff.getStaffid(), branchid, 1);
        }

        //4.进行返回信息
        PageInfo<OutLibrayVo> pageInfo = new PageInfo<>(librayVoList);
        PageBean<OutLibrayVo> pageBean = new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
        return Result.success(pageBean);
    }

    @Override
    public Result getOutInfoByCid(Integer cid, Integer page, Integer pageSize) {
        //1.开启分页
        PageHelper.startPage(page, pageSize);
        //2.进行查询
        List<OutLibrayGoods> librayGoodsList = outLibrayGoodsDao.selectOutLibrayGoodsByCid(cid);
        //3.设置返回信息
        PageInfo<OutLibrayGoods> pageInfo = new PageInfo<>(librayGoodsList);
        PageBean<OutLibrayGoods> pageBean = new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
        return Result.success(pageBean);
    }

    @Override
    @Transactional
    public Result warehouseAudit(OutLibray outLibray) {
        try {
            Staff staff = (Staff) session.getAttribute("staff");
            Integer branchid = staff.getBranchid();//分店编号
            Integer cid = outLibray.getCid(); //出库编号
            //判断审核状态  2通过，3驳回
            Integer examstate = outLibray.getExamstate();  //获取审核状态
            outLibray.setExamstaffid(staff.getStaffid());  //设置审核人
            outLibray.setExamtime(new Date(System.currentTimeMillis()));//设置审核时间
            if (examstate.equals(2)) { //代表通过
                //拿到商品详情
                List<OutLibrayGoods> librayGoodsList = outLibrayGoodsDao.selectOutLibrayGoodsByCid(cid);
                //查询商品库存是否超过入库的量
                for (OutLibrayGoods item : librayGoodsList) {
                    Integer num = item.getNum();//出库数量
                    Integer xid = item.getXid();//拿到出库主键
                    //现有库存
                    BranchGoods branchGoods = outLibrayGoodsDao.queryOutLibrayGoodsByXidAndBranchid(xid, branchid);
                    if (branchGoods.getCounts() < num) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                        return new Result(202, "库存已不足，请驳回检查", null);
                    }
                    //进行减少商品数量
                    this.reduceCounts(item, branchid);
                }
            }
            //进行审核操作
            outLibrayDao.updateOutLibray(outLibray);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return Result.error();
        }
        return Result.success();
    }

    /**
     * @param branchGoodsVoList
     * @return com.chb.model.vo.Result
     * @create by: 陈海彬
     * @description: 获取当前商品库存是否满足平调或出库
     * @create time: 2023/10/12 20:35
     */
    @Override
    public Result getOutLibrayCount(List<BranchGoodsVo> branchGoodsVoList) {
        for (BranchGoodsVo branchGoodsVo : branchGoodsVoList) {
            BranchGoods branchGoodsById = branchGoodsDao.getBranchGoodsById(branchGoodsVo.getId());
            if (branchGoodsById.getCounts() < branchGoodsVo.getIncounts()) {
                return new Result(202, "出库/平调/零售数量不能大于商品总量", null);
            }
        }
        return Result.success();
    }

    /**
     * @param outLibrayGoods 出库商品数据
     * @param branchid       分店id
     * @return void
     * @create by: 陈海彬
     * @description: 进行减少库存
     * @create time: 2023/9/29 10:42
     */
    @Transactional
    public void reduceCounts(OutLibrayGoods outLibrayGoods, Integer branchid) {
        Integer num = outLibrayGoods.getNum();//出库数量
        Integer xid = outLibrayGoods.getXid();//拿到出库主键
        BranchGoods branchGoods = outLibrayGoodsDao.queryOutLibrayGoodsByXidAndBranchid(xid, branchid);
        Integer counts = branchGoods.getCounts();//现有库存
        //进行减少库存
        branchGoods.setCounts(counts - num);
        branchGoodsDao.updateCounts(branchGoods);
    }
}